package com.github.tangyi.auth.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.oauth2.provider.token.store.redis.StandardStringSerializationStrategy;

import java.util.Map;

public class JsonRedisTokenStoreSerializationStrategy extends StandardStringSerializationStrategy {

    @Override
    protected <T> T deserializeInternal(byte[] bytes, Class<T> clazz) {

        Map<String, String> map = JSONObject.parseObject(bytes, Map.class);
        try {
            return (T) JSONObject.parseObject(map.get("valueToString"), Class.forName(map.get("valueToString")));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    protected byte[] serializeInternal(Object object) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", object.getClass().getName());
        jsonObject.put("valueToString", JSONObject.toJSONBytes(object));
        jsonObject.put("value", object);

        return JSONObject.toJSONBytes(jsonObject);
    }
}
